package com.jlnk.androidfmc.fragment.fragments;

import android.content.Intent;
import android.widget.TextView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.androidfmc.FourthActivity;
import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.adapter.ProductAdapter;
import com.jlnk.androidfmc.entity.Product;
import java.util.ArrayList;
import java.util.List;

public class SearchResultsFragment extends Fragment implements ProductAdapter.OnProductClickListener { // 正确实现接口

    private ProductAdapter adapter;
    private List<Product> products;

    public static SearchResultsFragment newInstance(List<Product> products) {
        SearchResultsFragment fragment = new SearchResultsFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList("PRODUCTS", new ArrayList<>(products));
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_search_results, container, false);

        // 初始化 RecyclerView
        RecyclerView rv_search_results = view.findViewById(R.id.rv_search_results);
        TextView tv_no_results = view.findViewById(R.id.tv_no_results);

        products = getArguments().getParcelableArrayList("PRODUCTS");

        // 设置 RecyclerView 为两列布局
        rv_search_results.setLayoutManager(new GridLayoutManager(getContext(), 2));

        adapter = new ProductAdapter(products);
        // 由于 SearchResultsFragment 实现了 OnProductClickListener，这里设置监听器是正确的
        adapter.setOnProductClickListener(this);
        rv_search_results.setAdapter(adapter);

        // 根据产品列表是否为空来显示或隐藏“没有找到相关结果”的提示
        if (products.isEmpty()) {
            tv_no_results.setVisibility(View.VISIBLE);
            rv_search_results.setVisibility(View.GONE);
        } else {
            tv_no_results.setVisibility(View.GONE);
            rv_search_results.setVisibility(View.VISIBLE);
        }

        return view;
    }

    @Override
    public void onProductClick(View view, Product product) {
        // 当某个产品项被点击时，此方法会被调用
        Intent intent = new Intent(view.getContext(), FourthActivity.class);
        // 将产品信息作为额外数据传递给 FourthActivity
        intent.putExtra("PRODUCT", product); // 假设您已经在 FourthActivity 中定义了接收 PRODUCT 额外数据的逻辑
        view.getContext().startActivity(intent);
    }
}